/*
 * Copyright 2011-2013, David George, Licensed under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.magneato.service;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.magneato.dto.MagUser;
import org.magneato.dto.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class TransactionLogger {
	@Autowired
	private JavaMailSender mailSender;

	@Value("${fromEmail}")
	private String adminEmail;

	private final Log _logger = LogFactory.getLog(TransactionLogger.class);

	public void logUpdate(final Page page, final String subject) {
		ExecutorService executorService = Executors.newSingleThreadExecutor();

		executorService.execute(new Runnable() {
			public void run() {

				try {
					final JAXBContext context = JAXBContext
							.newInstance(Page.class);

					final Marshaller marshaller = context.createMarshaller();
					marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
							Boolean.TRUE);
					marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
					marshaller.setProperty(Marshaller.JAXB_FRAGMENT,
							Boolean.TRUE);

					StringWriter writer = new StringWriter();
					final BufferedWriter os = new BufferedWriter(writer);
					os.write("<?xml version='1.0' encoding='UTF-8' standalone='yes'?><pages>");

					marshaller.marshal(page, os);
					os.write("</pages>");
					os.close();
					_logger.info(writer.toString());
				} catch (JAXBException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				if (adminEmail != null && !adminEmail.isEmpty()) {

					SimpleMailMessage message = new SimpleMailMessage();
					message.setTo(adminEmail);
					message.setFrom(adminEmail);
					message.setSubject(subject);
					String text = subject + " page " + page.getName()
							+ " contents " + page.getContent();

					message.setText(text);
					mailSender.send(message);
				}
			}
		});

		executorService.shutdown();
	}

	public void logRegistration(final MagUser user) {
		ExecutorService executorService = Executors.newSingleThreadExecutor();

		executorService.execute(new Runnable() {
			public void run() {
				SimpleMailMessage message = new SimpleMailMessage();
				message.setTo(adminEmail);
				message.setFrom(adminEmail);
				message.setSubject("New User Registration");

				String text = "New user registered " + user.toString();

				message.setText(text);
				mailSender.send(message);
			}
		});

		executorService.shutdown();
	}
}
